﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Shop.Wares.Models;
using Shop.Wares;
using Shop.Home.Services;
using PetaPoco;
using Shop.Users.Filters;
using Shop.Core.Models;
using System.Text;
using System.Web.Security;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.IO;
using Shop.User.Services;
using Shop.Wares.Repositories;

namespace Shop.Home.Controllers
{
    public class HomeController : Controller
    {
        UsersAccess UA = new UsersAccess();
        HomeAccess bll = new HomeAccess();
        Wares.Services.WaresAccess wbll = new Wares.Services.WaresAccess();
        WaresPictureAccess wpbll = new WaresPictureAccess();
        ShopCarAccess scbll = new ShopCarAccess();
        Shop.Order.Services.OrderAccess obll = new Order.Services.OrderAccess();
        Shop.Home.Services.WaresInventoryAccess wibll = new WaresInventoryAccess();

        CommentsAccess commentsAccess = new CommentsAccess();
        #region 前台商品的
        /// <summary>
        /// 首页
        /// </summary>
        /// <returns></returns>
        public ActionResult HomePage()
        {
            IList<Wares.Models.WaresCategory> wcinfo = wbll.GetWinfo();

            IList<Models.WaresPicture> wpinfo0 = wpbll.GetWPInfo(0);
            IList<Models.WaresPicture> wpinfo1 = wpbll.GetWPInfo(1);
            ViewBag.wpinfo0 = wpinfo0;
            ViewBag.wpinfo1 = wpinfo1;

            return View(wcinfo);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="Top"></param>
        /// <param name="CID"></param>
        /// <param name="CName"></param>
        /// <returns></returns>
        public ActionResult _WaresTopCategory(int Top,int CID,string CName)
        {
            IList<Wares.Models.Wares> winfo = bll.GetTopWInfo(Top,CID);
            ViewBag.CName = CName;
            return View(winfo);
        }
        /// <summary>
        /// 商品类别界面
        /// </summary>
        /// <param name="CID">类别ID</param>
        /// <param name="SCID">子类别ID</param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Category(int CID ,int SCID)
        {
            //获取所有类别信息
            IList<Wares.Models.WaresCategory> wcinfo = wbll.GetWinfo();
            ViewBag.wcinfo = wcinfo;
            if (SCID == 0)
            {
                //获取当前类别或子类别信息
                Shop.Wares.Models.WaresCategory winfo = bll.GetWCInfo(CID);
                ViewBag.winfo = winfo;
                ViewBag.IF = 0;
                //获取最新的商品
                IList<Wares.Models.Wares> nwinfo = bll.GetNowWInfo(5, CID, 0);
                ViewBag.nwinfo = nwinfo;
            }
            else
            {
                //获取当前类别或子类别信息
                Shop.Wares.Models.WaresCategory winfo = bll.GetWCInfo(CID);
                Shop.Wares.Models.SonWaresCategory swinfo = bll.GetSWCInfo(SCID);
                ViewBag.winfo = winfo;
                ViewBag.swinfo = swinfo;
                ViewBag.IF = 1;
                IList<Wares.Models.Wares> nwinfo = bll.GetNowWInfo(5, CID, SCID);
                ViewBag.nwinfo = nwinfo;
            }
            return View();
        }
        /// <summary>
        /// 前台类别页面的左侧类别的子类别
        /// </summary>
        /// <param name="CID">类别ID</param>
        /// <returns></returns>
        public ActionResult _SonCategory(int CID)
        {
            IList<Shop.Wares.Models.SonWaresCategory> swcinfo = wbll.GetSWInfo(CID);
            return View(swcinfo);
        }
        /// <summary>
        /// 前台商品类别的主要商品信息
        /// </summary>
        /// <param name="page">第几页</param>
        /// <param name="itemsPerPage">每页多少行</param>
        /// <param name="CID">类别ID</param>
        /// <param name="SCID">子类别ID</param>
        /// <param name="WName">商品名</param>
        /// <param name="OrderBy">排序字段名</param>
        /// <param name="Lift">升降序标志，0升序，1降序DESC</param>
        /// <returns></returns>
        public ActionResult _WaresCategory(long page, long itemsPerPage, int CID, int SCID, string WName, string OrderBy, int Lift)
        {
            
            PetaPoco.Page<Shop.Wares.Models.Wares> winfo = bll.GetHomeSerchWaresInfo(page, itemsPerPage, CID, SCID, WName, OrderBy, Lift);
            return View(winfo);
        }
        /// <summary>
        /// 前台商品类别的主要商品信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult _WaresCategory()
        {
            int page;
            int.TryParse(Request.Form["page"], out page);
            int itemsPerPage;
            int.TryParse(Request.Form["itemsPerPage"], out itemsPerPage);
            int CID;
            int.TryParse(Request.Form["CID"], out CID);
            int SCID;
            int.TryParse(Request.Form["SCID"], out SCID);
            string WName = Request.Form["WName"];
            string OrderBy = Request.Form["OrderBy"];
            int Lift;
            int.TryParse(Request.Form["Lift"], out Lift);
            PetaPoco.Page<Shop.Wares.Models.Wares> winfo = bll.GetHomeSerchWaresInfo(page, itemsPerPage, CID, SCID, WName, OrderBy, Lift);
            return View(winfo);
        }
        /// <summary>
        /// 分布页子类别
        /// </summary>
        /// <param name="CID"></param>
        /// <returns></returns>  
        public ActionResult _LayoutCategory(int CID)
        {
            IList<Shop.Wares.Models.SonWaresCategory> swcinfo = wbll.GetSWInfo(CID);
            return View(swcinfo);
        }
        /// <summary>
        /// 商品详情页
        /// </summary>
        /// <returns></returns>
        public ActionResult WaresProduct(int WID)
        {
            Shop.Wares.Models.AnyWares winfo = bll.GetWInfo(WID);
            return View(winfo);
        }
        /// <summary>
        /// 搜索结果页
        /// </summary>
        /// <returns></returns>
        [ValidateInput(false)]
        public ActionResult WaresSearch()
        {
            //获取搜索内容
            string WName = Request.QueryString["Search"];
            ViewBag.WName = WName;
            //获取所有类别信息
            IList<Wares.Models.WaresCategory> wcinfo = wbll.GetWinfo();
            ViewBag.wcinfo = wcinfo;
            //获取最新的商品
            IList<Wares.Models.Wares> nwinfo = bll.GetNowWInfo(5, 0, 0);
            ViewBag.nwinfo = nwinfo;
            return View();
        }
        #endregion

        #region 用户的
        /// <summary>
        /// 用户退出
        /// </summary>
        /// <returns></returns>
        public ActionResult UserQuit()
        {
            try
            {
                Shop.User.UserState.DelInfo();
            }
            catch (Exception)
            {
                return Content("NO");
                throw;
            }
            return Content("OK");
        }
        /// <summary>
        /// 用户中心
        /// </summary>
        /// <returns></returns>
        [Login]
        public ActionResult UserCenter()
        {
            return View();
        }
        #endregion
        #region 购物车
        /// <summary>
        /// 加入购物车
        /// </summary>
        /// <returns></returns>
        public ActionResult AddShopCar()
        {
            //获取当前用户信息
            Shop.User.Models.UsersInfo uinfo = 
                Shop.User.UserState.GetUserState();
            if (uinfo == null)
            {
                return Content("User");
            }
            int WID = Convert.ToInt32(Request.Form["WID"]);
            int BuyNum = Convert.ToInt32(Request.Form["BuyNum"]);
            AnyWares winfo = bll.GetWInfo(WID);
            Models.BuyCar bcinfo = new Models.BuyCar();
            bcinfo.UID = uinfo.UID;bcinfo.WID = WID;
            bcinfo.UnitPrice = winfo.PPrice;
            bcinfo.BuyNum = BuyNum;
            bcinfo.MoneyTotal = BuyNum * winfo.PPrice;
            bcinfo.CreateDate = DateTime.Now;
            //判断库存
            if (wibll.GetWaresStock(WID, BuyNum) == 1)
            {
                return Content("NO1");
            }
            try
            {
                scbll.AddShopCar(bcinfo);
            }
            catch (Exception)
            {
                return Content("NO");
            }
            //减少库存
            if (wibll.ReduceWares(WID,BuyNum) == 0)
            {
                return Content("NO");
            }
            return Content("OK");
        }
        /// <summary>
        ///购物车
        /// </summary>
        /// <returns></returns>
        [Login]
        public ActionResult ShopCar()
        {
            return View();
        }
        /// <summary>
        /// 购物车的分布页
        /// </summary>
        /// <returns></returns>
        public ActionResult _ShopCar()
        {
            //获取当前用户信息
            Shop.User.Models.UsersInfo uinfo = Shop.User.UserState.GetUserState();
            IList<Models.AnyBuyCar> bcinfo = scbll.GetBCInfo(uinfo.UID);
            return View(bcinfo);
        }
        /// <summary>
        /// 删除购物车中的商品
        /// </summary>
        /// <returns></returns>
        public ActionResult DelShopCar()
        {
            User.Models.UsersInfo uinfo = 
                Shop.User.UserState.GetUserState();
            if (uinfo == null)
            {
                return Content("User");
            }
            int BCID = Convert.ToInt32(Request.Form["BCID"]);
            Shop.Home.Models.BuyCar bcinfo = scbll.GetBCInfoByID(BCID);
            //删除购物车中的商品
            if (scbll.DelShopCar(BCID) == 0)
            {
                return Content("NO");
            }
            //增加库存
            if (wibll.ReduceWares(bcinfo.WID, -bcinfo.BuyNum) == 0)
            {
                return Content("NO");
            }
            return Content("OK");
        }
        /// <summary>
        /// 布局页购物车
        /// </summary>
        /// <returns></returns>
        public ActionResult _HomeShopCar()
        {
            //获取当前用户信息
            Shop.User.Models.UsersInfo uinfo = Shop.User.UserState.GetUserState();
            IList<Models.AnyBuyCar> bcinfo = scbll.GetBCInfo(uinfo.UID);
            //商品数量
            int WNum = 0;
            //钱
            double MonNum = 0;
            for (int i = 0; i < bcinfo.Count; i++)
            {
                WNum += bcinfo[i].BuyNum;
                MonNum += bcinfo[i].MoneyTotal;
            }
            ViewBag.WNum = WNum;
            ViewBag.MonNum = MonNum;
            return View();
        }
        /// <summary>
        /// 结算页面
        /// </summary>
        /// <returns></returns>
        public ActionResult _Settlement()
        {
            Shop.User.Models.UsersInfo uinfo = Shop.User.UserState.GetUserState();
            if (uinfo == null)
            {
                return Content("User");
            }
            double MoneyTotal = Convert.ToDouble(Request.Form["MoneyTotal"]);
            ViewBag.MoneyTotal = MoneyTotal;
            return View();
        }
        /// <summary>
        /// 检查库存
        /// </summary>
        /// <returns></returns>
        public ActionResult CheckInventory()
        {
            //获取当前用户信息
            Shop.User.Models.UsersInfo uinfo = Shop.User.UserState.GetUserState();
            //获取购物车的信息
            IList<Models.AnyBuyCar> bcinfo = scbll.GetBCInfo(uinfo.UID);

            string NullWare = "";
            for (int i = 0; i < bcinfo.Count; i++)
            {
                if (wibll.GetWaresStock(bcinfo[i].WID,bcinfo[i].BuyNum) == 1)
                {
                    NullWare += bcinfo[i].WName;
                }
            }
            if (NullWare != "")
            {
                return Content(NullWare);
            }
            return Content("OK");
        }


        #endregion

        #region 支付
        /// <summary>
        /// 生成订单
        /// </summary>
        /// <returns></returns>
        public ActionResult _OrderPay()
        {
            string Address = Request.Form["Address"];
            string UName = Request.Form["UName"];
            string Tel = Request.Form["Tel"];
            string IDCard = Request.Form["IDCard"];
            //获取当前用户信息
            Shop.User.Models.UsersInfo uinfo = Shop.User.UserState.GetUserState();
            if (uinfo == null)
            {
                return Content("User");
            }
            //获取购物车的信息
            IList<Models.AnyBuyCar> bcinfo = scbll.GetBCInfo(uinfo.UID);
            Session["AnyBuyCar"] = bcinfo;
            Session["Address"] = Address;
            Session["UName"] = UName;
            Session["Tel"] = Tel;
            Session["IDCard"] = IDCard;
            //获取订单号
            string OrderNumber = obll.GetOrderNumber();
            //总价格
            double MoneyTotal = 0;
            //总数量
            int Number = 0;
            //循环创建订单详情
            for (int i = 0; i < bcinfo.Count; i++)
            {
                try
                {
                    MoneyTotal += bcinfo[i].MoneyTotal;
                    Number += bcinfo[i].BuyNum;
                }
                catch (Exception)
                {
                    return Content("NO");
                }
            }
            //生成订单
            DateTime CreateDate = DateTime.Now;
            //送货地址
            ViewBag.Address = Address;
            //收货人姓名
            ViewBag.UName = UName;
            //电话
            ViewBag.Tel = Tel;
            //订单号
            ViewBag.OrderNumber = OrderNumber;
            //总金额
            ViewBag.MoneyTotal = MoneyTotal * 100;
            //总数量
            ViewBag.Number = Number;
            //编码
            ViewBag.inputCharset = "1";
            //订单时间
            ViewBag.CreateDate = CreateDate.ToString("yyyyMMddhhmmss");
            //支付方式
            ViewBag.payType = "0";

            //订单提交地址
            ViewBag.serverUrl = "/Home/PaySucceed";
            return View();
        }
        /// <summary>
        /// 支付成功后
        /// </summary>
        /// <returns></returns>
        public ActionResult PaySucceed()
        {
            //获取当前用户信息
            User.Models.UsersInfo uinfo = Shop.User.UserState.GetUserState();
            if (uinfo == null)
            {
                return Content("User");
            }
            //获取购物车的信息
            IList<Models.AnyBuyCar> bcinfo =
                (IList<Models.AnyBuyCar>)Session["AnyBuyCar"];
            //获取订单号
            string OrderNumber = obll.GetOrderNumber();
            //总价格
            double MoneyTotal = 0;
            //总数量
            int Number = 0;
            //循环创建订单详情
            for (int i = 0; i < bcinfo.Count; i++)
            {
                try
                {
                    Order.Models.OrderDetail odinfo = 
                        new Order.Models.OrderDetail();
                    odinfo.OrderNumber = OrderNumber;
                    odinfo.WID = bcinfo[i].WID;
                    odinfo.UnitPrice = bcinfo[i].UnitPrice;
                    odinfo.BuyNum = bcinfo[i].BuyNum;
                    odinfo.MoneyTotal = bcinfo[i].MoneyTotal;
                    odinfo.CreateDate = DateTime.Now;
                    obll.CreateOrderDetail(odinfo);
                    MoneyTotal += bcinfo[i].MoneyTotal;
                    Number += bcinfo[i].BuyNum;
                    //增加销售量
                    wibll.AddSaleNum(bcinfo[i].WID, bcinfo[i].BuyNum);
                }
                catch (Exception)
                {
                    ViewBag.IfSuccess = "出现错误";
                    View();
                }
            }
            //生成订单
            DateTime CreateDate = DateTime.Now;
            try
            {
                Order.Models.Order oinfo =
                    new Order.Models.Order();
                oinfo.OrderNumber = OrderNumber;
                oinfo.UID = uinfo.UID;
                oinfo.MoneyTotal = MoneyTotal;
                oinfo.Number = Number;
                oinfo.UName = Session["UName"].ToString();
                oinfo.Tel = Session["Tel"].ToString();
                oinfo.Postcode = "";
                oinfo.Address = Session["Address"].ToString();
                oinfo.IfPay = 0;
                oinfo.Status = 0;
                oinfo.CreateDate = CreateDate;
                oinfo.CCode = "SF";
                oinfo.IDCard = "zz";
                obll.CreateOrder(oinfo);
            }
            catch (Exception ex)
            {
                ViewBag.IfSuccess = "出现错误,错误信息:"+ex.Message;
                View();
            }
            //删除购物车
            scbll.DelAllShopCar(uinfo.UID);
            ViewBag.OrderNumber = OrderNumber;
            ViewBag.IfSuccess = "成功";
            return View();
        }
        #endregion

        #region 订单管理
        /// <summary>
        /// 用户订单管理
        /// </summary>
        /// <returns></returns>
        [Login]
        public ActionResult UserOrder()
        {
            return View();
        }
        /// <summary>
        /// 用户订单管理分布页
        /// </summary>
        /// <returns></returns>
        public ActionResult _UserOrder()
        {
            //获取当前用户信息
            Shop.User.Models.UsersInfo uinfo = Shop.User.UserState.GetUserState();
            if (uinfo == null)
            {
                return Content("User");
            }
            int Page;
            int.TryParse(Request.Form["Page"],out Page);
            if (Page<=0)
            {
                Page = 1;
            }
           
            Page<Shop.Order.Models.AnyOrder> oinfo = obll.GetUserOInfo(Page,10,uinfo.UID);
            return View(oinfo);
        }
        /// <summary>
        /// 用户订单详情页
        /// </summary>
        /// <returns></returns>
        [Login]
        public ActionResult _UserOrderDetail()
        {
            string OrderNumber = Request.Form["OrderNumber"];
            IList<Shop.Order.Models.AnyOrderDetail> odinfo = obll.GetUserODInfo(OrderNumber);
            return View(odinfo);
        }



        #endregion


        /// <summary>
        /// 下载电子书的方法
        /// </summary>
        /// <param name="WID"></param>
        /// <returns></returns>
        public FileResult _DownloadBook(int WID)
        {
                var filePath = wbll.GetWaresInfo(WID).bookLocation;


                filePath = Server.MapPath(filePath).Replace("Home","Shop");
                if (System.IO.File.Exists(filePath))
                {
                   return File(filePath, "text/plain", wbll.GetWaresInfo(WID).WName+ ".txt"); //welcome.txt是客户端保存的名字
                }
            else
            {
                return null;
            }

        }



        /// <summary>
        /// 获取用户的信息，页面
        /// </summary>
        /// <returns></returns>
        [Login]
        public ActionResult UserInfo()
        {
            //获取当前用户信息
            Shop.User.Models.UsersInfo uinfo = Shop.User.UserState.GetUserState();
           
            return View(uinfo);
        }

        /// <summary>
        /// 更新用户的信息，页面
        /// </summary>
        /// <returns></returns>
        [Login]
        public ActionResult UpdateUserInfo()
        {
            Shop.User.Models.UsersInfo uinfo = Shop.User.UserState.GetUserState();
            return View(uinfo);
        }

        /// <summary>
        /// 更新用户的信息，处理逻辑
        /// </summary>
        /// <returns></returns>
        [Login]
        [HttpPost]
        public ActionResult UpdateUserInfoPost()
        {
            string UName = Request.Form["UName"];
            string Tel = Request.Form["Tel"];
            string UPass = Request.Form["UPass"];
            string Email = Request.Form["Email"];

            UA.UpdateUser("update Shop_User set UPass = @0,tel = @1,Email = @2 where UName = @3", UPass,Tel,Email,UName);
            Shop.User.Models.UsersInfo uinfo = UA.SelectUser(UName);
            Shop.User.UserState.SaveUserState(uinfo);
            return View("UserInfo", uinfo);
        }

        public string AddComments(string comments,int WID)
        {
            Shop.User.Models.UsersInfo uinfo = Shop.User.UserState.GetUserState();
            var insertNum = Convert.ToInt32(commentsAccess.AddComments(new Comments { 
                Comment = comments,
                UID = uinfo.UID,
                WID = WID,
                CommentDate = DateTime.Now

           }));
            if (insertNum ==0)
            {
                return "-1";
            }
            else
            {
                return "0";
            }
        }
    }
}    